package com.ljkj.zjf.rest;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljkj.common.application.SpringApplicationContext;
import com.ljkj.common.db.util.MD5Util;
import com.ljkj.zjf.common.CacheManager;
import com.ljkj.zjf.common.GlobalNames;
import com.ljkj.zjf.service.TuserService;

import ch.qos.logback.core.net.SyslogOutputStream;

@Path("rest/access")
public class AccessResource {

	private static TuserService tuserService;
	private static Logger logger = LoggerFactory.getLogger(AccessResource.class);
	
	//初始化service
	static {
		tuserService  = (TuserService) SpringApplicationContext.getBean("tuserService");
	}
	
	@Path("/admin_login")
	@POST
	@Produces("application/json; charset=utf-8")
	public String loginToSystem(String json_para,@Context HttpServletRequest request) throws Exception {
		
		System.out.println("===================");
		
		String decode_str = URLDecoder.decode(json_para, "utf-8");

		JSONObject json_object = JSON.parseObject(decode_str);
		String username = json_object.getString("username"); 
		String password = json_object.getString("password");
		String imgCode = json_object.getString("captcha");
		
		Map<String, Object> errorMap = new HashMap<String, Object>();
		errorMap.put("errCode", GlobalNames.CALL_RESULT_FAIL);

		// 1.验证imgCode非空
		if (null == imgCode || "".equals(imgCode)) {
			errorMap.put("errMsg", "请输入验证码");
			return JSON.toJSONString(errorMap);
		} else {
			
			//获取imgCode的值，和用户输入的验证码进行对比。
			String matchRes = CacheManager.getSession().getIfPresent("imgCode");
			if (!matchRes.equals(imgCode)) {
				errorMap.put("errMsg", "验证码不正确");
				return JSON.toJSONString(errorMap);
			}
		}
		if (username == null || "".equals(username.replace(" ", ""))) {
			errorMap.put("errMsg", "用户名不能为空");
			return JSON.toJSONString(errorMap);
		}else if(password == null || "".equals(password.replace(" ", ""))){
			errorMap.put("errMsg", "密码不能为空");
			return JSON.toJSONString(errorMap);
		}
		password = MD5Util.md5Hex(password);
		String result = this.tuserService.adminLogin(username,password);
		
		System.out.println(result);
		return result;
	}

}
